package com.dart.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dart.commons.base.service.BaseService;
import com.dart.sys.entity.Resource;
import com.dart.sys.mapper.ResourceMapper;
import com.dart.sys.service.ResourceService;

@Service
public class ResourceServiceImpl extends BaseService<Resource, Integer> implements ResourceService {
	
	@Autowired
	private ResourceMapper mapper ;
	
	@Override
	public boolean insertSelective(Resource entity) {
		return super.insertSelective(entity);
	}
	
	@Override
	public boolean delete(Integer id) {
		return super.delete(id);
	}
	
	@Override
	public boolean updateSelective(Resource entity) {
		return super.updateSelective(entity);
	}
	
	@Override
	public Resource selectById(Integer id) {
		return super.selectById(id);
	}
	
	@Override
	public List<Resource> selectList(Resource entity, String orderByField) {
		return super.selectList(entity, orderByField);
	}
	
	@Override
	public List<Resource> selectRoots() {
		return this.mapper.selectRoots();
	}

	@Override
	public List<Resource> selectChildrenById(Integer id) {
		return this.mapper.selectChildrenById(id);
	}
	
	public List<Resource> recursiveResource(Integer id) {
		List<Resource> allList = new ArrayList<Resource>() ;
		
		List<Resource> list = null ;
		if(null == id) {
			list = this.mapper.selectRoots() ;
			for (Resource resource : list) {
				allList.add(handlerRecursive(resource)) ;
			}
		} else {
			allList.add(handlerRecursive(this.selectById(id))) ;
		}
		return allList ;
	}
	
	private Resource handlerRecursive(Resource resource) {
		
		List<Resource> childrens = this.mapper.selectChildrenById(resource.getId()) ;
		if(null != childrens) {
			List<Resource> children = new ArrayList<Resource>() ;
			for (Resource child : childrens) {
				children.add(child) ;
				this.handlerRecursive(child) ;
			}
			resource.setChildren(children);
		}
		
		return resource;
	}

}
